package zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;



/**
 * 感觉就是 Zip[In/Out]putStream 把所连接的流“分段并压缩”
 */
public class ZIPCompress {

	public static void main(String[] args) throws Exception {
		FileOutputStream fos = new FileOutputStream("test1.zip");
		CheckedOutputStream cos = new CheckedOutputStream(fos, new Adler32());
		ZipOutputStream zos = new ZipOutputStream(cos);
		BufferedOutputStream bos = new BufferedOutputStream(zos);
		
		zos.setComment("A test of Java Zipping"); // No corresponding getComment(), though.

		for (int i = 0; i < args.length; i++) {
			System.out.println("Writing file: " + args[i]);
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(args[i]));
			zos.putNextEntry(new ZipEntry(args[i]));
			int c;
			while (-1 != (c = bis.read())) {
				bos.write(c);
			}
			bis.close();
		}
		bos.close();

		// Checksum valid only after the file has been closed!
		System.out.println("Checksum: " + cos.getChecksum().getValue());

		// Now extract the files:
		System.out.println("Extract file:");

		FileInputStream fis = new FileInputStream("test1.zip");
		CheckedInputStream cis = new CheckedInputStream(fis, new Adler32());
		ZipInputStream zis = new ZipInputStream(cis);
		BufferedInputStream bis = new BufferedInputStream(zis);

		ZipEntry ze;
		while (null != (ze = zis.getNextEntry())) {
			System.out.println("Reading file: " + ze);
			int b;
			while (-1 != (b = bis.read())) {
				System.out.write(b);
			}
		}

		// Alternative way to open and read zip files;
		/*
		ZipFile zf = new ZipFile("test1.zip");
		Enumeration e = zf.entries();
		while(e.hasMoreElements()) {
			ZipEntry zipEntry = (ZipEntry)e.nextElement();
			System.out.println("File: " + zipEntry);
			// ... and extract the data as before
		}
		*/
		System.out.println("Checksum: " + cis.getChecksum().getValue());
		bis.close();
	}
}
